package com.example.core.service;

import com.example.core.adapter.SysReceiverAdapter;
import org.jgroups.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

@Service
public class JGroupsServiceImpl implements JGroupsService, InitializingBean, DisposableBean {

    Logger logger = LoggerFactory.getLogger(getClass());

    private JChannel channel;

    @Override
    public void afterPropertiesSet() throws Exception {
        this.startChannel();
    }

    @Override
    public void destroy() throws Exception {
        this.stopChannel();
    }

    @Override
    public void startChannel() throws Exception {
        this.channel = new JChannel("jgroups-udp.xml");
        this.channel.setReceiver(new SysReceiverAdapter());
        this.channel.connect(DEFAULT);
    }

    @Override
    public void stopChannel() throws Exception {
        channel.close();
    }

    @Override
    public void send(Address address, Message message) throws Exception {
        this.channel.send(address, message);
    }

    @Override
    public void broadcast(Object message) throws Exception {
        this.channel.send(null, message);
    }

    @Override
    public JChannel getChannel() {
        return channel;
    }
}
